package com.example.aop;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author yanzhao
 * @date 2022/6/2 16:15
 * @since 1.0.0
 */
public class ReflectiveMethodInvocation implements MethodInvocation {

    private List<Object> methodInterceptors;

    protected final Object proxy;

    protected final Object target;

    protected final Method method;

    protected Object[] arguments;

    private int currentInterceptorIndex = -1;

    public ReflectiveMethodInvocation(Object proxy, Object target, Method method, Object[] arguments, List<Object> methodInterceptors) {
        this.proxy = proxy;
        this.target = target;
        this.method = method;
        this.arguments = arguments;
        this.methodInterceptors = methodInterceptors;
    }

    @Override
    public Object proceed() throws Throwable {
        if (this.currentInterceptorIndex == this.methodInterceptors.size() - 1) {
            return invokeJoinpoint();
        }
        MethodInterceptor methodInterceptor = (MethodInterceptor) methodInterceptors.get(++currentInterceptorIndex);

        return methodInterceptor.invoke(this);
    }

    protected Object invokeJoinpoint() throws Throwable {
        return method.invoke(this.target, this.arguments);
    }

    @Override
    public Object[] getArguments() {
        return this.arguments;
    }

    @Override
    public Method getMethod() {
        return this.method;
    }

    @Override
    public Object getThis() {
        return this.target;
    }
}
